package com.example.demo.Controller.Topic;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.Entity.UserInfo.Userinfo;
import com.example.demo.ServiceImpl.Topic.TopicServiceImpl;
import com.example.demo.Entity.Topic.Topic;
import com.example.demo.ServiceImpl.UserInfo.UserinfoServiceImpl;
import com.example.demo.Utils.JWTUtils.JWTUtils;
import com.example.demo.Utils.RedisUtils.RedisUtil;
import com.example.demo.Utils.Result.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/topic")
@Tag(name = "TopicController", description = "TopicController 相关接口")
public class TopicController {

    @Resource
    private TopicServiceImpl topicService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private UserinfoServiceImpl userinfoService;

    @Resource
    private RedisUtil redisUtil;

    @PostMapping
    @Operation(summary = "保存或更新 Topic 信息", description = "根据传入的 Topic 对象保存或更新信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "保存或更新成功", content = @Content(schema = @Schema(implementation = Boolean.class)))
    })
    public Boolean save(@RequestBody Topic topic, HttpServletRequest request) {
// 保存或更新数据后，删除相关缓存
        redisUtil.deleteKeysStartingWith("topic");
        if (topic.getCreateUserId() == null) {
            String token = request.getHeader("Authorization");
            Integer userId = Integer.parseInt(JWTUtils.getUserIDFromToken(token));
            topic.setCreateUserId(userId);
            topic.setCreateTime(new Date());
        }
        return topicService.saveOrUpdate(topic);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "根据 ID 删除 Topic 信息", description = "根据传入的 ID 删除对应的 Topic 信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功", content = @Content(schema = @Schema(implementation = Boolean.class)))
    })
    public Boolean delete(@PathVariable(value = "id") Integer id) {
// 删除数据后，删除相关缓存
        redisTemplate.delete("topic:all");
        redisTemplate.delete("topic:id:" + id);
        redisUtil.deleteKeysStartingWith("topic");
        return topicService.removeById(id);
    }

    @GetMapping
    @Operation(summary = "获取所有 Topic 信息", description = "获取所有 Topic 的列表信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = R.class)))
    })
    public R findAll() {
        List<Topic> topicList = topicService.list();
        return R.ok().put("topicList", topicList);
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据 ID 获取 Topic 信息", description = "根据传入的 ID 获取对应的 Topic 信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = R.class)))
    })
    public R findOne(@PathVariable(value = "id") Integer id) {
        String key = "topic:id:" + id;
        Topic topic = (Topic) redisTemplate.opsForValue().get(key);
        if (topic == null) {
            topic = topicService.getById(id);
            if (topic != null) {
                redisTemplate.opsForValue().set(key, topic, 60, TimeUnit.MINUTES);
            }
        }
        return R.ok().put("topic", topic);
    }

    @GetMapping("/page")
    @Operation(summary = "分页获取 Topic 信息", description = "根据传入的页码和每页数量分页获取 Topic 信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = R.class)))
    })
    @Parameter(name = "pageNum", in = ParameterIn.QUERY, description = "页码", required = true)
    @Parameter(name = "pageSize", in = ParameterIn.QUERY, description = "每页数量", required = true)
    @Parameter(name = "keyword", in = ParameterIn.QUERY, description = "搜索关键字")
    public R findPage(@RequestParam(value = "pageNum") Integer pageNum,
                      @RequestParam(value = "pageSize") Integer pageSize,
                      @RequestParam(value = "keyword", required = false) String keyword) {
        String key = "topic:page:" + pageNum + ":" + pageSize + ":" + keyword;
        @SuppressWarnings("unchecked")
        Page<Topic> topicPage = (Page<Topic>) redisTemplate.opsForValue().get(key);
        List<String> UserNickNames;
        if (topicPage == null) {
            LambdaQueryWrapper<Topic> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.orderByDesc(Topic::getTopicId);
            if (keyword != null) {
                queryWrapper.like(Topic::getTopicName, keyword);
                LambdaQueryWrapper<Userinfo> userinfoQueryWrapper = new LambdaQueryWrapper<>();
                userinfoQueryWrapper.like(Userinfo::getNickname, keyword);
                List<Userinfo> userinfoList = userinfoService.list(userinfoQueryWrapper);
                List<Integer> userIds = new ArrayList<>();
                for (Userinfo userinfo : userinfoList) {
                    userIds.add(userinfo.getUserId());
                }
                if (!userIds.isEmpty()) {
                    queryWrapper.or().in(Topic::getCreateUserId, userIds);
                }
            }
            topicPage = topicService.page(new Page<>(pageNum, pageSize));
            redisTemplate.opsForValue().set(key, topicPage, 60, TimeUnit.MINUTES);
        }
        UserNickNames = new ArrayList<>();
        for (Topic topic : topicPage.getRecords()) {
            LambdaQueryWrapper<Userinfo> userinfoQueryWrapper = new LambdaQueryWrapper<>();
            userinfoQueryWrapper.eq(Userinfo::getUserId, topic.getCreateUserId());
            Userinfo userinfo = userinfoService.getOne(userinfoQueryWrapper);
            if (userinfo != null) {
                UserNickNames.add(userinfo.getNickname());
            } else {
                UserNickNames.add("");
            }
        }
        return R.ok().put("topicPage", topicPage).put("UserNickNames", UserNickNames);
    }
}